// 用户信息仓库
import { defineStore } from "pinia";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/util";
import type { loginForm, loginResponseData, logoutResponseData, userResponseData } from "@/api/user/type";
import type { UserState } from "./types/type";
import { constantsRoute } from "@/router/routes";

const useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantsRoute,
      username: "",
      avatar: ""
    };
  },
  actions: {
    // 用户登录
    async userLogin(data: loginForm) {
      const res: loginResponseData = await reqLogin(data);
      console.log(res);
      if (res.code === 200) {
        this.token = res.data as string;
        SET_TOKEN(res.data as string);
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    // 获取用户数据
    async userInfo() {
      const res: userResponseData = await reqUserInfo();
      console.log(res);
      if (res.code === 200) {
        this.username = res.data.username;
        this.avatar = res.data.avatar;
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    // 退出登录
    async userLogout() {
      const res: logoutResponseData = await reqLogout();
      if (res.code !== 200) return Promise.reject(new Error(res.message));
      //  清空仓库数据 清空token
      REMOVE_TOKEN();
      this.token = "";
      this.username = "";
      this.avatar = "";
      return "ok";
    }
  },
  getters: {}
});

export default useUserStore;
